/*
 * Copyright (c) 2025 EasyAdmin
 * All rights reserved.
 *
 * This file is part of the [EasAdmin] project.
 * Unauthorized copying of this file, via any medium, is strictly prohibited.
 * Proprietary and confidential.
 *
 * Author: EasyAdmin ( 1073602@qq.com )
 * Website: https://www.xhxiao.com
 */
package com.easy.module.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.framework.common.exception.ServiceException;
import com.easy.framework.common.utils.AssertUtil;
import com.easy.framework.common.utils.ConvertUtil;
import com.easy.framework.common.utils.Func;
import com.easy.framework.security.model.Dept;
import com.easy.module.system.cache.DeptCache;
import com.easy.module.system.cache.PostCache;
import com.easy.module.system.entity.SysDept;
import com.easy.module.system.entity.SysPost;
import com.easy.module.system.entity.SysUserDept;
import com.easy.module.system.mapper.SysUserDeptMapper;
import com.easy.module.system.query.SysUserDeptQuery;
import com.easy.module.system.service.ISysDeptService;
import com.easy.module.system.service.ISysUserDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户部门 Service业务
 *
 * @author EasyAdmin ( 1073602@qq.com )
 * @date 2025-08-19
 */
@RequiredArgsConstructor
@Service
public class SysUserDeptServiceImpl extends ServiceImpl<SysUserDeptMapper, SysUserDept> implements ISysUserDeptService {

    final ISysDeptService sysDeptService;


    @Override
    public boolean addUserDept(SysUserDept userDept) {
        SysDept dept = sysDeptService.getById(userDept.getDeptId());
        if (count(lambdaQueryWrapper().eq(SysUserDept::getUserId, userDept.getUserId())
                .eq(SysUserDept::getDeptId, userDept.getDeptId())
                .eq(SysUserDept::getPostId, userDept.getPostId())) > 0) {
            throw new ServiceException("已在[" + dept.getDeptName() + "]该岗位");
        }
        userDept.setOrgId(dept.getOrgId());
        return save(userDept);
    }

    @Override
    public boolean updateUserDept(SysUserDept userDept) {
        SysUserDept entity = getById(userDept.getId());
        AssertUtil.isFalse(Func.isEmpty(entity), "数据不存在");
        SysDept dept = sysDeptService.getById(userDept.getDeptId());
        if (count(lambdaQueryWrapper()
                .ne(SysUserDept::getId, userDept.getId())
                .eq(SysUserDept::getUserId, userDept.getUserId())
                .eq(SysUserDept::getDeptId, userDept.getDeptId())
                .eq(SysUserDept::getPostId, userDept.getPostId())) > 0) {
            throw new ServiceException("已在[" + dept.getDeptName() + "]该岗位");
        }
        userDept.setOrgId(dept.getOrgId());
        return updateById(userDept);
    }

    @Override
    public List<SysUserDept> queryList(SysUserDeptQuery query) {
        List<SysUserDept> list = ConvertUtil.convert(list(lambdaQuery(query)), SysUserDept.class);
        if (Func.isNotEmpty(list)) {
            list.forEach(item -> {
                if (Func.isNotEmpty(item.getOrgId()) && item.getOrgId() > 0) {
                    item.setOrgName(DeptCache.get(item.getOrgId()).map(SysDept::getDeptName).orElse(""));
                }
                if (Func.isNotEmpty(item.getDeptId()) && item.getDeptId() > 0) {
                    item.setDeptName(DeptCache.get(item.getDeptId()).map(SysDept::getDeptName).orElse(""));
                }
                if (Func.isNotEmpty(item.getPostId()) && item.getPostId() > 0) {
                    item.setPostName(PostCache.get(item.getPostId()).map(SysPost::getPostName).orElse(""));
                }
            });
        }
        return list;
    }

    @Override
    public List<SysUserDept> listByUserId(Long userId) {
        return list(lambdaQueryWrapper().eq(SysUserDept::getUserId, userId));
    }

    @Override
    public List<Long> getPostIdListByUserId(Long userId) {
        List<SysUserDept> list = listByUserId(userId);
        return Optional.ofNullable(list).orElse(new ArrayList<>()).stream().map(SysUserDept::getPostId).collect(Collectors.toList());
    }

    @Override
    public boolean hasUserByDeptId(Long deptId) {
        return count(lambdaQueryWrapper().eq(SysUserDept::getDeptId, deptId)) > 0;
    }


    @Override
    public List<Dept> getDeptByUserId(Long userId) {
        List<Dept> deptList = new ArrayList<>();
        if (Func.isNotEmpty(userId)) {
            List<SysUserDept> userDeptList = listByUserId(userId);
            if (Func.isNotEmpty(userDeptList)) {
                userDeptList.forEach(ud -> {
                    deptList.add(new Dept(ud.getOrgId(), ud.getDeptId(), ud.getPostId()));
                });
            }
        }
        return deptList;
    }
}
